package com.chenfy.everysound.ui.main

import android.util.Log
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chenfy.everysound.R
import com.chenfy.everysound.base.BASE_URL
import com.chenfy.everysound.base.BaseVH
import com.chenfy.everysound.entity.SoundItem

class SoundAdapter : RecyclerView.Adapter<BaseVH>() {
    var datas: List<SoundItem> = listOf()
        set(value) {
            field = value
            notifyDataSetChanged()
        }
    val downloadSet = mutableSetOf<String>()

    var playingItem = -1

    fun addDownload(pos:Int){
        downloadSet.add(datas[pos].id)
        notifyItemChanged(pos)
    }

    fun removeDownload(pos: Int){
        downloadSet.remove(datas[pos].id)
        notifyItemChanged(pos)
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        BaseVH(R.layout.item_sound, parent)


    override fun onBindViewHolder(holder: BaseVH, position: Int) {
        val soundItem = datas[position]
        holder.setImg(BASE_URL + soundItem.img, R.id.soundIv)
        holder.setText(soundItem.name,R.id.soundNameTv)
        holder.visible(soundItem.id in downloadSet, R.id.itemProgress)

        Glide.with(holder.itemView)
            .load(R.mipmap.sound)
            .into(holder.getView(R.id.playIv))

        holder.visible(position == playingItem, R.id.playIv)
    }

    fun showPlayingItem(id:String){
        if (id.isNotBlank()) {
            playingItem = datas.indexOfFirst {
                id == it.id
            }
            Log.d("Chen","playingItem: ${playingItem}")
            if (playingItem >=0) {
                notifyItemChanged(playingItem)
            }
        }else{
            dismissPlayingItem()
        }
    }

    private fun dismissPlayingItem(){
        if (playingItem >= 0){
            val current = playingItem
            playingItem = -1
            notifyItemChanged(current)
        }
    }

    override fun getItemCount() = datas.size
}